
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:proj_sfv/component/MyNotification.dart';
import 'package:proj_sfv/domain/UserVo.dart';
import 'package:proj_sfv/domain/Video.dart';
import 'package:proj_sfv/domain/videoVo.dart';
import 'package:proj_sfv/http/api.dart';
import 'package:proj_sfv/http/requests.dart';
import 'package:proj_sfv/pages/myVideoDetailPage.dart';
import 'package:proj_sfv/store/MyArguments.dart';

enum VideoPageType {
  MY, LIKE, COLLECT, DISLIKE, COMMON
}

class SimpleVideo extends StatefulWidget {
  VideoPageType type;
  SimpleVideo(this.type);

  @override
  State<SimpleVideo> createState() => _SimpleVideoState();
}

class _SimpleVideoState extends State<SimpleVideo> {
  // TODO 请求获得列表
  List<VideoVo> data = [];
  String title;
  MyArguments args;

  @override
  void didChangeDependencies() {
    args = ModalRoute.of(context).settings.arguments as MyArguments;
    print('request args: ${args.type} ${args.id} ${args.token}');
    if (args.type == VideoPageType.MY) {
      getMyVideosRequest(context, args.token, args.id).then((value) async {
        if (value == null) {
          return;
        }
        setState(() {
          data = value;
        });
      });
    } else if (args.type == VideoPageType.LIKE || args.type == VideoPageType.DISLIKE) {
      getLikeVideosRequest(context, args.id, args.token,
          args.type == VideoPageType.LIKE ? VideoPreference.LIKE : VideoPreference.DISLIKE).then((value) async {
        if (value == null) {
          return;
        }
        setState(() {
          data = value;
        });
      });
    } else if (args.type == VideoPageType.COLLECT) {
      getMyCollectByNameRequest(context, args.id, args.token, args.collectName).then((value) async {
        if (value == null) {
          return;
        }
        setState(() {
          data = value;
        });
      });
    }
    super.didChangeDependencies();
  }

  @override
  void initState() {
    switch (widget.type) {
      case VideoPageType.LIKE:
        title = "点赞的视频";
        break;
      case VideoPageType.MY:
        title = "我的视频";
        break;
      case VideoPageType.DISLIKE:
        title = "点踩的视频";
        break;
      case VideoPageType.COLLECT:
        title = "收藏夹";
        break;
    }
    super.initState();
  }


  _itemClick (VideoVo e) async {
      if (widget.type == VideoPageType.MY) {
        Map<String, VideoVo> result = await Navigator.push(
            context, MaterialPageRoute(builder: (context) =>
            MyVideoDetailPage(
                e, true, args.token, _myVideoDeleteOps, _myVideoUpdateOps)));
        print('delete result ${result.entries.first.key} ${result.entries.first.value}');
      if (result != null && result.entries.first.key == 'delete') {
        setState(() {
            data.remove(result.entries.first.value);
          });
        }
      } else if (widget.type == VideoPageType.LIKE ||
          widget.type == VideoPageType.DISLIKE) {
        Map<String, VideoVo> result = await Navigator.push(
            context, MaterialPageRoute(builder: (context) =>
            MyVideoDetailPage(e, false, args.token, _likeVideoDeleteOps, null,
              type: widget.type,)));
        if (result != null) {
          if (result.entries.first.key == 'delete') {
            setState(() {
              data.remove(result.entries.first.value);
            });
          }
        }
      } else if (widget.type == VideoPageType.COLLECT) {
        Map<String, VideoVo> result = await Navigator.push(
            context, MaterialPageRoute(builder: (context) =>
            MyVideoDetailPage(
              e, false, args.token, _collectVideoDeleteOps, null,
              type: widget.type, collectName: args.collectName,)));
        if (result != null) {
          if (result.entries.first.key == 'delete') {
            setState(() {
              data.remove(result.entries.first.value);
            });
          }
        }
      }
  }

  _myVideoDeleteOps(VideoVo e) async {
      String result = await showDialog(context: context, builder: (builder) => MyNotification("确认要删除视频？", [
        TextButton(onPressed: () async {
          String result = await deleteMyVideoRequest(context, args.token, e.videoId);
          if (result != null) {
            Fluttertoast.showToast(msg: result);
            Navigator.pop(context, "confirm");
          }
        }, child: Text("确认")),
        TextButton(onPressed: () => Navigator.pop(context, "cancel"), child: Text("取消"))
      ]));
      if (result == "confirm") {
        Navigator.pop(context, <String, VideoVo>{'delete': e});
      }
  }

  _myVideoUpdateOps(Video v, VideoVo vo) async {
    setState(() {
      vo.videoName = v.videoName;
    });
  }

  _likeVideoDeleteOps(VideoVo e, VideoPreference type) async {
    String result = await showDialog(context: context, builder: (builder) => MyNotification("确认要删除视频？", [
      TextButton(onPressed: () async {
        String result = await cancelLikeVideoRequest(context, args.id ,args.token, e.videoId, type == VideoPageType.LIKE ?
        VideoPreference.LIKE : VideoPreference.DISLIKE);
        if (result != null) {
          Fluttertoast.showToast(msg: result);
          Navigator.pop(context, "confirm");
        }
      }, child: Text("确认")),
      TextButton(onPressed: () => Navigator.pop(context, "cancel"), child: Text("取消"))
    ]));
    if (result == "confirm") {
      Navigator.pop(context, <String, VideoVo>{'delete': e});
    }
  }

  _collectVideoDeleteOps(VideoVo e, String collectName) async {
    String result = await showDialog(context: context, builder: (builder) => MyNotification("确认要删除视频？", [
      TextButton(onPressed: () async {
        String result = await deleteCollectorItemRequest(context, args.id ,args.token, collectName, e.videoId, );
        if (result != null) {
          Fluttertoast.showToast(msg: result);
          Navigator.pop(context, "confirm");
        }
      }, child: Text("确认")),
      TextButton(onPressed: () => Navigator.pop(context, "cancel"), child: Text("取消"))
    ]));
    if (result == "confirm") {
      Navigator.pop(context, <String, VideoVo>{'delete': e});
    }
  }

  @override
  Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Text(title),
        ),
        body: GridView.count(
            crossAxisCount: 2,
            mainAxisSpacing: 8,
          crossAxisSpacing: 8,
          padding: EdgeInsets.all(8),
          childAspectRatio: 1,
          children: data.map<Widget>((e) {
              return InkWell(
                  onTap: () => _itemClick(e),
                  child: VideoItem(e)
              );
          }).toList(),
        ),
      );
  }
}

class VideoItem extends StatelessWidget {
  final VideoVo videoVo;


  VideoItem(this.videoVo);

  @override
  Widget build(BuildContext context) {
    String imageUrl = Uri.https(cosHost3, '${videoVo.profileUrl}.jpeg').toString();
    final Widget image = Semantics(
      label: videoVo.videoName,
      child: Material(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
        clipBehavior: Clip.antiAlias,
        child: Image.network(
          imageUrl,
          fit: BoxFit.cover,
        ),
      ),
    );
    return GridTile(
      footer: Material(
        color: Colors.transparent,
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(bottom: Radius.circular(4)),
        ),
        clipBehavior: Clip.antiAlias,
        child: GridTileBar(
          backgroundColor: Colors.black45,
          title: _GridTitleText(videoVo.videoName),
        ),
      ),
      child: image,
    );
  }
}

class _GridTitleText extends StatelessWidget {
  const _GridTitleText(this.text);

  final String text;

  @override
  Widget build(BuildContext context) {
    return FittedBox(
      fit: BoxFit.scaleDown,
      alignment: AlignmentDirectional.centerStart,
      child: Text(text),
    );
  }
}